<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      width="40%"
      :title="getTitle"
      @ok="handleSubmit"
    >
      <BasicForm @register="registerForm">
        <template #coverUrlSlot="{ model, field }">
          <Spin :spinning="spinning">
            <Upload
              v-model:file-list="fileList"
              name="file"
              list-type="picture-card"
              :show-upload-list="false"
              :action="uploadImgApi"
              :before-upload="beforeUpload"
              @change="handleChange(field)"
            >
              <img v-if="model[field]" :src="model[field]" alt="avatar" />
              <div v-else>
                <div class="ant-upload-text">点击上传</div>
              </div>
            </Upload>
          </Spin>
          <div class="hint">建议图片尺寸：宽750*高440rpx</div>
        </template>

        <template #areaSpecSlot="{ model, field }">
          <div class="school">
            <Input placeholder="请输入" v-model:value="model[field]" />
            <a-button type="primary" class="btn" @click="handleAddSchool"> 添加区域特色 </a-button>
          </div>
        </template>
        <template #areaSpecDeleteSlot="{ model, field }">
          <div class="school">
            <Input placeholder="请输入" v-model:value="model[field]" />
            <a-button danger class="btn" @click="handleDeleteAreaSpec(field)">
              删除区域特色
            </a-button>
          </div>
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { buildingFormSchema } from './communityManage.data';
  import { defineComponent, ref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Spin, Upload, Input } from 'ant-design-vue';

  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      Spin,
      Upload,
      Input,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const getTitle = ref('');
      const isUpdate = ref(false);
      const spinning = ref(false);
      const fileList = ref<any[]>([]);
      const uploadImgApi = '';
      const countAreaSpec = ref(0);
      const areaSpecArr = ref<any[]>([]);

      // 表单
      const [
        registerForm,
        { setFieldsValue, resetFields, validate, appendSchemaByField, removeSchemaByFiled },
      ] = useForm({
        labelWidth: 140,
        schemas: buildingFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      // 模态框
      const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = data.isUpdate;
        if (data.isUpdate) {
          getTitle.value = '编辑社区';
          setFieldsValue({
            ...data.record,
          });
        } else {
          getTitle.value = '新增社区';
        }
      });

      const handleSubmit = async () => {
        try {
          // 表单校验
          const values = await validate();
          // 开启确定按钮的加载状态
          setModalProps({ confirmLoading: true });
          const { createMessage } = useMessage();
          values.areaSpecType = areaSpecArr.value;
          console.log(values);

          if (isUpdate.value) {
            // 编辑
            createMessage.success('编辑社区');
          } else {
            // 新增
            createMessage.success('新增社区');
          }
          emit('success');
          closeModal();
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      };

      // 上传前
      const beforeUpload = () => {
        console.log('beforeUpload');
      };

      const handleChange = (field) => {
        console.log('handleChange');
        const obj = {};
        obj[field] = 'pic-url';
        setFieldsValue(obj);
      };

      const handleAddSchool = () => {
        appendSchemaByField(
          {
            field: 'newAreaSpec-' + countAreaSpec.value,
            label: '区域特色',
            component: 'Input',
            slot: 'areaSpecDeleteSlot',
            dynamicRules: () => {
              return [
                {
                  required: true,
                  message: '请输入区域特色',
                },
              ];
            },
          },
          'areaSpec'
        );
        areaSpecArr.value.push({
          field: 'newAreaSpec-' + countAreaSpec.value,
        });
        countAreaSpec.value++;
        console.log(areaSpecArr.value);
      };

      const handleDeleteAreaSpec = (field) => {
        const index = field.split('-')[1];
        console.log(index);

        removeSchemaByFiled('newAreaSpec' + '-' + index);
        let Index = -1;
        areaSpecArr.value.forEach((item: any, i) => {
          if (item.field.indexOf(index) !== -1) {
            Index = i;
          }
        });
        console.log(Index);

        areaSpecArr.value.splice(Index, 1);
        countAreaSpec.value--;
        console.log(areaSpecArr.value);
      };

      return {
        getTitle,
        registerForm,
        registerModal,
        handleSubmit,
        spinning,
        fileList,
        uploadImgApi,
        beforeUpload,
        handleChange,
        handleAddSchool,
        handleDeleteAreaSpec,
      };
    },
  });
</script>

<style scoped lang="less">
  .school {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn {
      margin-left: 10px;
    }
  }
</style>
